package com.example.cloudmusic

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.example.cm_base.BaseViewModel
import com.example.cm_player.model.SongInfo
import com.example.cm_player.manager.PlayerStateManager
import com.example.cm_player.service.PlayerService
import com.example.cm_utils.ContextHelper

class MainViewModel : BaseViewModel() {
    private var playerService: PlayerService? = null
    private var bound = false

    // 服务连接
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as PlayerService.PlayerBinder
            playerService = binder.getService()
            bound = true
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            playerService = null
            bound = false
        }
    }

    /**
     * 绑定播放服务
     */
    fun bindPlayerService() {
         ContextHelper.context.get()?.let {
            val intent = Intent(it, PlayerService::class.java)
            it.bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    fun startService(){
        ContextHelper.context.get()?.let {
            val intent = Intent(it, PlayerService::class.java)
            it.startService(intent)
        }
    }

    /**
     * 解绑播放服务
     */
    fun unbindPlayerService() {
        if (bound) {
            ContextHelper.context.get()?.unbindService(connection)
            bound = false
        }
    }

    /**
     * 播放歌曲
     */
    fun playSong(songInfo: SongInfo) {
        startService()
        playerService?.play(songInfo)
    }

    /**
     * 暂停/继续播放
     */

    fun pause(){
        playerService?.pause()
    }

    /**
     * 停止播放
     */
    fun stopPlayback() {
        playerService?.stop()
    }

    /**
     * 跳转到指定位置
     */
    fun seekTo(position: Float) {
        val currentSong = PlayerStateManager.currentPlayedMusic.value ?: return
        val targetPosition = (position * currentSong.duration / 100).toLong()
        playerService?.seekTo(targetPosition)
    }

    fun removeFromPlaylist(songInfo: SongInfo){
        playerService?.removeFromPlaylist(songInfo)
    }

    override fun onCleared() {
        super.onCleared()
        unbindPlayerService()
    }

    fun resume() {
        playerService?.resume()
    }
}